package com.nuanshui.heatedloan.credit.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.constant.RabbitMqQueue;
import com.nuanshui.heatedloan.credit.model.record.WhiteListResultRecord;
import com.nuanshui.heatedloan.credit.mongodb.WhiteListResultRecordRepository;
import com.nuanshui.heatedloan.middleware.rabbitmq.RabbitmqMessageHandler;
import com.nuanshui.heatedloan.middleware.rabbitmq.annotation.MqMessageHandler;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by wangxw on 2017/8/4.
 */

@MqMessageHandler(RabbitMqQueue.RABBIT_MQ_SAVE_WHITE_LIST)
public class SaveWhiteListHandler implements RabbitmqMessageHandler {

    @Autowired
    private WhiteListResultRecordRepository whiteListResultRecordRepository;

    private Logger logger = LoggerFactory.getLogger(RaiseLimitHandler.class);

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        try{
            logger.info("============"+"开始保存白名单数据"+"================");
            String msg = new String(message.getBody());
            WhiteListResultRecord whiteListResultRecord = JSON.parseObject(msg,WhiteListResultRecord.class);
            List<WhiteListResultRecord> querys=whiteListResultRecordRepository.findByPhone(whiteListResultRecord.getPhone());
            if(querys!=null&&querys.size()>0){
                for(WhiteListResultRecord whiteListResultRecordOld:querys){
                    whiteListResultRecordRepository.delete(whiteListResultRecordOld);
                }
            }
            whiteListResultRecordRepository.save(whiteListResultRecord);
            logger.info("============"+"保存白名单数据完成"+"================");
        }catch (Exception e){
            e.printStackTrace();
            LogUtil.error(logger, "----------------------保存黑名单数据保存-----------------------");
        }finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }
    }

}
